using BF.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace BF
{

    public class DialogRoot : MonoBehaviour
    {
        private static RectTransform _rectTransform;

        public static RectTransform rectTransform
        {
            get
            {
                if (_rectTransform == null)
                {
                    _rectTransform = instance.transform as RectTransform;
                }
                return _rectTransform;
            }
        }

        public static DialogRoot instance { get; private set; }
        public new static Camera camera { get; private set; }

        private static bool _isInited;

        public static void Init()
        {
            if (instance != null)
            {
                return;
            }

            GameObject prefab = Resources.Load<GameObject>("Dialog/DialogRoot");
            instance = Instantiate<GameObject>(prefab).GetComponent<DialogRoot>();
            DoInit();
        }

        public static void SetScale(Vector2Int scale)
        {
            if (instance == null)
            {
                Init();
            }
            CanvasScaler cs = instance.GetComponent<CanvasScaler>();
            cs.referenceResolution = scale;
        }

        public static void SetCanvasSortLayer(string layerName)
        {
            if (instance == null)
            {
                Init();
            }
            Canvas[] canvas = instance.GetComponentsInChildren<Canvas>();
            canvas.ForEach(it => it.sortingLayerName = layerName);
        }

        private void Awake()
        {
            this.gameObject.name = "DialogRoot";
            if (instance == null)
            {
                instance = this;
                DoInit();
            }
            else if (instance != this)
            {
                UnityEngine.Object.Destroy(this.gameObject);
            }
        }

        private static void DoInit()
        {
            if (_isInited)
            {
                return;
            }
            _isInited = true;

            camera = instance.transform.Find("UICamera").GetComponent<Camera>();

            UnityEngine.Object.DontDestroyOnLoad(instance.gameObject);
        }
    }
}
